<template>
  <div class="order-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的订单</span>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="orderList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="订单编号" width="100" />
        <el-table-column label="车辆信息" width="200">
          <template #default="scope">
            <div v-if="scope.row.vehicleInfo">
              {{ scope.row.vehicleInfo.brand }} {{ scope.row.vehicleInfo.model }}
            </div>
            <div v-else>
              <el-tag type="info">加载中...</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="取车地点" width="200">
          <template #default="scope">
            <div v-if="scope.row.startShopInfo">
              {{ scope.row.startShopInfo.shopName }}
            </div>
            <div v-else>
              <el-tag type="info">加载中...</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="还车地点" width="200">
          <template #default="scope">
            <div v-if="scope.row.endShopInfo">
              {{ scope.row.endShopInfo.shopName }}
            </div>
            <div v-else>
              <el-tag type="info">加载中...</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="租车时间">
          <template #default="scope">
            <div>{{ formatDate(scope.row.startTime) }}</div>
            <div>至</div>
            <div>{{ formatDate(scope.row.endTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="订单金额" width="120">
          <template #default="scope">
            <span class="price">¥ {{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
              {{ scope.row.status === 0 ? '进行中' : '已完成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewOrderDetail(scope.row.id)"
            >
              查看详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              type="danger" 
              size="small" 
              @click="cancelOrder(scope.row.id)"
            >
              取消订单
            </el-button>
            <el-button 
              v-if="scope.row.status === 1 && !scope.row.hasEvaluation" 
              type="success" 
              size="small" 
              @click="evaluateOrder(scope.row.id)"
            >
              评价
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 评价对话框 -->
    <el-dialog title="评价订单" v-model="evaluationDialogVisible" width="500px">
      <el-form :model="evaluationForm" label-width="100px">
        <el-form-item label="评分">
          <el-rate v-model="evaluationForm.score" :max="5" show-score></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input type="textarea" v-model="evaluationForm.content" rows="4" placeholder="请输入您的评价内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserOrders, cancelOrder as apiCancelOrder } from '@/api/order'
import { getVehicleDetail } from '@/api/vehicle'
import * as apiEvaluation from '@/api/evaluation'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const currentUserId = localStorage.getItem('userId')
const evaluationDialogVisible = ref(false)
const currentOrderId = ref(null)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10
})

// 评价表单
const evaluationForm = reactive({
  score: 5,
  content: ''
})

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取订单列表
const getOrderList = async () => {
  if (!currentUserId) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  loading.value = true
  try {
    const res = await getUserOrders(currentUserId, queryParams)
    orderList.value = res.data.records
    total.value = res.data.total
    
    // 获取每个订单的车辆和车行信息
    fetchOrderDetails()
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单详细信息（车辆、车行）
const fetchOrderDetails = async () => {
  if (!orderList.value || orderList.value.length === 0) return
  
  for (const order of orderList.value) {
    try {
      // 获取车辆信息
      const vehicleRes = await getVehicleDetail(order.vehicleId)
      order.vehicleInfo = vehicleRes.data
      
      // 车行信息可以在后续添加
      order.startShopInfo = { shopName: `取车地点ID: ${order.startShopId}` }
      order.endShopInfo = { shopName: `还车地点ID: ${order.endShopId}` }
      
      // 默认没有评价
      order.hasEvaluation = false
    } catch (error) {
      console.error(`获取订单${order.id}详情失败:`, error)
    }
  }
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 取消订单
const cancelOrder = (orderId) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await apiCancelOrder(orderId)
      ElMessage.success('订单取消成功')
      getOrderList() // 刷新列表
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {})
}

// 评价订单
const evaluateOrder = (orderId) => {
  currentOrderId.value = orderId
  evaluationForm.score = 5
  evaluationForm.content = ''
  evaluationDialogVisible.value = true
}

// 提交评价
const submitEvaluation = async () => {
  try {
    const evaluationData = {
      orderId: currentOrderId.value,
      userId: Number(localStorage.getItem('userId') || 0),
      shopId: orderList.value.find(o => o.id === currentOrderId.value)?.startShopId,
      score: evaluationForm.score,
      content: evaluationForm.content
    };
    
    const res = await apiEvaluation.submitEvaluation(evaluationData);
    
    if (res.data && res.data.success) {
      ElMessage.success('评价提交成功');
      evaluationDialogVisible.value = false;
      
      // 刷新列表并标记已评价
      const order = orderList.value.find(o => o.id === currentOrderId.value);
      if (order) {
        order.hasEvaluation = true;
      }
      
      getOrderList(); // 刷新订单列表
    } else {
      ElMessage.error(res.data?.message || '评价提交失败');
    }
  } catch (error) {
    console.error('评价提交失败:', error);
    ElMessage.error('评价提交失败');
  }
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getOrderList()
}

// 每页条数变化
const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  getOrderList()
}

// 组件挂载时获取数据
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 